<template>


	<view class="container">


		<!-- 触发按钮 -->
		<button @click="openDialog" class="add-btn">+ 新增任务</button>

		<!-- 弹窗组件 -->
		<uni-popup ref="taskDialog" type="center" :mask-click="false">
			<view class="dialog-container">
				<!-- 标题栏 -->
				<view class="dialog-header">
					<text>新增任务</text>
					<uni-icons type="closeempty" size="24" @click="closeDialog" />
				</view>

				<!-- 表单内容 -->
				<scroll-view scroll-y class="dialog-content">
					<!-- 任务编号 -->
					<view class="form-row">
						<text class="label required">任务编号</text>
						<input v-model="formData.taskRegNumber" @input="handleSearch" placeholder="请输入任务编号" />
					</view>

					<!-- 搜索结果列表 -->
					<scroll-view v-if="showResult" class="result-list" scroll-y>
						<view v-for="(item,index) in resultList" :key="index" class="result-item"
							@click="selectItem(item)">
							<view>{{ item }}</view>
						</view>
						<view v-if="resultList.length === 0" class="empty-tip">
							暂无搜索结果
						</view>
					</scroll-view>



					<!-- 检查时间 -->
					<view class="form-row">
						<text class="label required">检查时间</text>
						<view class="time-range">
							<uni-datetime-picker v-model="startDate" placeholder="开始日期" />
							<text>至</text>
							<uni-datetime-picker v-model="endDate" placeholder="结束日期" />
						</view>
					</view>

					<!-- 部门选择 -->
					<view class="form-row">
						<text class="label required">选择部门</text>
						<picker mode="selector" :range="departments" range-key="deptName" :value="selectedIndex"
							@change="handleDeptChange">
							<view class="picker">
								部门:{{ selectedDept.deptName}}
							</view>
						</picker>
					</view>

					<!-- 部门选择 -->
					<view class="form-row">
						<text class="label required">抄送人选择</text>
						<picker mode="selector" :range="users" range-key="nickName" :value="selectedIndexus"
							@change="handleCcChange">
							<view class="picker">
								抄送人:
							</view>
						</picker>
					</view>


					<!-- 抄送人选择 -->
					<!-- 					<view class="form-row">
						<text class="label">选择抄送人</text>
						<picker mode="multiSelector" @change="handleCcChange" :range="ccUserList">
							<view>{{ ccUsersText || '请选择抄送人' }}</view>
						</picker>
					</view> -->

					<!-- 已选抄送人 -->
					<view class="form-row" v-if="formData.userIds.length">
						<text class="label">已选抄送人</text>
						<view class="selected-users">
							{{ ccUserList.join('、') }}
						</view>
					</view>
				</scroll-view>

				<!-- 操作按钮 -->
				<view class="dialog-footer">
					<button @click="closeDialog">取消</button>
					<button type="primary" @click="handleSubmit">立即创建</button>
				</view>
			</view>
		</uni-popup>



		<!-- 月份切换 -->
		<view class="header">
			<text @click="prevMonth">◀</text>
			<text>{{ currentYear }}年{{ currentMonth }}月</text>
			<text @click="nextMonth">▶</text>
		</view>

		<!-- 星期标题 -->
		<view class="week-header">
			<text v-for="day in weekDays" :key="day">{{ day }}</text>
		</view>

		<!-- 日期格子 -->
		<view class="days-grid">
			<view v-for="(day, index) in visibleDays" :key="index" :class="['day-cell', {
          'current-month': day.isCurrentMonth,
          'has-data': hasData(day),
          'today': isToday(day)
        }]" @click="showDetail(day)">
				<text>{{ day.date }}</text>
			</view>
		</view>



		<!-- 日期详情弹窗 -->
		<uni-popup ref="popup" type="bottom" style="height: 100%;">
			<scroll-view scroll-y="true" style="max-height: 60vh;">
				<view class="popup-content">
					<text class="date-title">{{ selectedDate }}</text>
					<view v-if="currentData.length > 0" class="data-list">
						<view v-for="(item, idx) in currentData" :key="idx" class="data-item">

							<view class="card">
								<view class="progress-list">
									<view class="progress-item">
										<text>任务编号:{{ item.taskRegNumber }}</text>
									</view>
									<view class="progress-item">
										<text>开始时间:{{ item.taskStartTime }} </text>
									</view>
									<view class="progress-item">
										<text>结束时间:{{ item.taskEndTime }} </text>
									</view>
									<view class="progress-item">
										<text>部门名:{{ item.deptName }} </text>
									</view>
									<view class="progress-item">
										<text>用户名:{{ item.userName }} </text>
									</view>
								</view>
							</view>
						</view>
					</view>
					<view v-else class="no-data">当日无数据</view>
				</view>
			</scroll-view>
		</uni-popup>
	</view>



</template>

<script>
	import {
		calendarList,
		selectDeptTree,
		selectUserByDeptId,
		addrl,
		contractListrl
	} from "@/api/calender";
	export default {
		data() {
			return {
				isTask:false,
				cract: [],
				showResult: false,
				resultList: [],
				sourceData: [{
						id: 1,
						name: '苹果1'
					},
					{
						id: 2,
						name: '苹果2'
					},
					{
						id: 3,
						name: '橙子'
					},
					{
						id: 4,
						name: '西瓜'
					},
					{
						id: 5,
						name: '葡萄'
					}
				],
				formData: {
					taskRegNumber: '',
					deptId: '',
					time: [],
					userIds: []
				},
				startDate: '',
				endDate: '',
				selectedIndex: 0,
				selectedIndexus: 0,
				selectedDept: {
					deptId: '',
					deptName: ''
				},
				selectedUser: {
					userId: '',
					nickName: ''
				},
				departments: [],
				ccUserList: [],
				users: [],
				formDataRl: {
					date: ''
				},
				weekDays: ['日', '一', '二', '三', '四', '五', '六'],
				currentYear: new Date().getFullYear(),
				currentMonth: new Date().getMonth() + 1,
				// 模拟数据 { '2025-5-20': [{content: '会议'}] }
				allData: {
					'2025-5-15': [{
						content: '项目评审'
					}],
					'2025-5-20': [{
						content: '生日派对'
					}, {
						content: '团队会议'
					}]
				},
				currentData: [],
				selectedDate: ''
			}
		},
		computed: {
			visibleDays() {
				const days = []
				const firstDay = new Date(this.currentYear, this.currentMonth - 1, 1)
				const startWeekDay = firstDay.getDay()
				const daysInMonth = new Date(this.currentYear, this.currentMonth, 0).getDate()

				// 上个月末尾几天
				for (let i = 0; i < startWeekDay; i++) {
					const date = new Date(this.currentYear, this.currentMonth - 1, -i)
					days.unshift({
						date: date.getDate(),
						month: date.getMonth() + 1,
						year: date.getFullYear(),
						isCurrentMonth: false
					})
				}

				// 当月天数
				for (let i = 1; i <= daysInMonth; i++) {
					days.push({
						date: i,
						month: this.currentMonth,
						year: this.currentYear,
						isCurrentMonth: true
					})
				}

				// 下个月开头几天
				const totalCells = Math.ceil(days.length / 7) * 7
				for (let i = 1; days.length < totalCells; i++) {
					days.push({
						date: i,
						month: this.currentMonth + 1 > 12 ? 1 : this.currentMonth + 1,
						year: this.currentMonth + 1 > 12 ? this.currentYear + 1 : this.currentYear,
						isCurrentMonth: false
					})
				}

				return days
			},
			ccUsersText() {
				return this.formData.userIds.length ? this.formData.userIds.join('、') : ''
			}
		},
		created() {
			// 页面加载时调用接口  
			this.list();
			this.getDeptList();
		},
		methods: {
			selectItem(item) {
				uni.showToast({
					title: `已选择: ${item}`,
					icon: 'none'
				})
				this.formData.taskRegNumber = item
				this.showResult = false
			},
			handleSearch() {
				if (this.formData.taskRegNumber != '') {
					const taskNumber=this.formData.taskRegNumber;
					contractListrl(taskNumber).then((response) => {
							this.cract = response.data.splice(0,5);
							console.log(response)
							
						})
						.catch(() => {
							
						});
					setTimeout(() => {				
						this.resultList = this.cract;
						this.showResult = true
					}, 500)
				} else {
					this.showResult = false
				}
				console.log(this.isTask)

			},
			handleDeptChange(e) {
				this.selectedIndex = e.detail.value;
				this.formData.deptId = this.departments[this.selectedIndex].deptId;
				this.selectedDept.deptName = this.departments[this.selectedIndex].deptName;
				// 根据部门ID获取用户列表
				selectUserByDeptId(this.formData.deptId).then(response => {
					this.users = response.data;
				});
				// 实际使用时这里可以emit事件或更新表单
				this.$emit('change', this.selectedDept.deptId)
			},
			getDeptList() {
				selectDeptTree('business').then((response) => {
					console.log("获取部门列表");
					console.log(response.data);
					this.departments = response.data
				})
				console.log(this.departments)
			},
			openDialog() {
				this.formData = {
						taskRegNumber: '',
						deptId: '',
						time: [],
						userIds: []
					},
					this.startDate = '';
				this.endDate = '';
				this.$refs.taskDialog.open()
			},
			closeDialog() {
				this.$refs.taskDialog.close()
			},
			handleCcChange(e) {
				console.log("----");

				this.selectedIndexus = e.detail.value;
				if (!this.formData.userIds.includes(this.users[this.selectedIndexus].userId)) {
					this.formData.userIds.push(this.users[this.selectedIndexus].userId);
				}
				this.selectedUser.nickName = this.users[this.selectedIndexus].nickName;
				const selectedName = this.selectedUser.nickName;
				if (!this.ccUserList.includes(selectedName)) {
					this.ccUserList.push(selectedName)
				}
			},
			handleSubmit() {
				if (!this.validateForm()) return
				this.formData.time = [],
					this.formData.time.push(this.startDate.split(' ')[0])
				this.formData.time.push(this.endDate.split(' ')[0])
				console.log('提交数据:', this.formData)
				// addrl(this.formData).then(response => {
				// 	if (response.msg === '操作成功') {  
				// 	  this.$modal.msgSuccess("新增成功");  
				// 	  this.addDialogVisible = false;  
				// 			this.formData= {
				// 				taskRegNumber: '',
				// 				deptId: '',
				// 				time: [],
				// 				userIds: []
				// 			 };
				// 		}  
				// 	});
				// this.$refs.taskDialog.close()
			},
			validateForm() {
				// contractListrl(this.formData.taskRegNumber).then((response) => {
				// 		console.log("1111111")
				// 	.catch(() => {
				// 		console.log("22222222")
				// 	});
				// });
				if (!this.formData.taskRegNumber) {
					uni.showToast({
						title: '请输入任务编号',
						icon: 'none'
					})
					return false
				}
				if (!this.startDate || !this.endDate) {
					uni.showToast({
						title: '请选择检查时间',
						icon: 'none'
					})
					return false
				}
				const timestampA = new Date(this.startDate).getTime()
				const timestampB = new Date(this.endDate).getTime()
				if (timestampA > timestampB) {
					uni.showToast({
						title: '结束时间不得小于开始时间',
						icon: 'none'
					})
					return false
				}



				if (!this.formData.deptId) {
					uni.showToast({
						title: '请选择部门',
						icon: 'none'
					})
					return false
				}
				return true
			},
			// 部门选择变化时触发
			onDepartmentChange(e) {
				this.selectedDepartment = this.departments[e.detail.value];
			},

			// 抄送人选择变化时触发
			onAssigneeChange(e) {
				// 单选场景
				this.selectedAssignee = this.assignees[e.detail.value];

				// 如果是多选场景，可以在这里处理已选抄送人列表
				// 例如：this.selectedAssignees.push(this.assignees[e.detail.value]);
			},
			// 登录成功后，处理函数
			list() {

			},
			prevMonth() {
				if (this.currentMonth === 1) {
					this.currentYear--
					this.currentMonth = 12
				} else {
					this.currentMonth--
				}
			},
			nextMonth() {
				if (this.currentMonth === 12) {
					this.currentYear++
					this.currentMonth = 1
				} else {
					this.currentMonth++
				}
			},
			hasData(day) {
				const key = `${day.year}-${day.month}-${day.date}`
				return this.allData[key] && this.allData[key].length > 0
			},
			isToday(day) {
				const today = new Date()
				return day.year === today.getFullYear() &&
					day.month === today.getMonth() + 1 &&
					day.date === today.getDate()
			},
			showAdd() {
				this.showModal = true;
			},
			showDetail(day) {
				const key = `${day.year}-${day.month}-${day.date}`
				console.log(key + "***");
				this.formDataRl.date = key;
				calendarList(this.formDataRl).then(res => {
					this.currentData = res.rows;
				})
				this.selectedDate = `${day.year}年${day.month}月${day.date}日`
				// this.currentData = this.allData[key] || []
				this.$refs.popup.open()
			}
		}
	}
</script>

<style>
	.container {
		padding: 20rpx;
	}

	.header {
		display: flex;
		justify-content: space-between;
		padding: 30rpx 0;
		font-size: 36rpx;
		font-weight: bold;
	}

	.week-header {
		display: flex;
		justify-content: space-around;
		padding: 20rpx 0;
		border-bottom: 1rpx solid #eee;
	}

	.days-grid {
		display: grid;
		grid-template-columns: repeat(7, 1fr);
		gap: 10rpx;
		margin-top: 10rpx;
	}

	.day-cell {
		aspect-ratio: 1;
		display: flex;
		justify-content: center;
		align-items: center;
		border-radius: 10rpx;
		background-color: #f5f5f5;
	}

	.current-month {
		background-color: #fff;
	}

	.today {
		border: 2rpx solid #007AFF;
	}

	.has-data {
		background-color: #4CD964;
		color: white;
	}

	.popup-content {
		padding: 40rpx;
		background: white;
		border-radius: 20rpx 20rpx 0 0;
	}

	.date-title {
		font-size: 36rpx;
		font-weight: bold;
		display: block;
		margin-bottom: 30rpx;
	}

	.data-list {
		margin-top: 20rpx;
	}

	.data-item {
		padding: 20rpx 0;
		border-bottom: 1rpx solid #eee;
	}

	.no-data {
		text-align: center;
		color: #999;
		padding: 40rpx 0;
	}

	/* 卡片样式 */
	.card {
		margin-bottom: 10px;
		background-color: #fff;
		border-radius: 8px;
		padding: 10px;
		box-shadow: 0px 2px 4px rgba(0, 0, 0, 0.1);
	}

	.card-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding-bottom: 5px;
		border-bottom: 1px solid #eee;
	}

	.card-title {
		font-size: 16px;
		font-weight: bold;
		color: #333;
	}

	.card-action {
		font-size: 14px;
		color: #007aff;
	}

	/* 卡片内容 */
	.card-content {
		display: flex;
		align-items: center;
		margin: 10px 0;
	}

	.big-number {
		font-size: 24px;
		font-weight: bold;
		color: royalblue;
		margin-right: 5px;
	}

	/* 卡片底部 */
	.card-footer {
		font-size: 12px;
		color: #666;
		display: flex;
		justify-content: space-between;
	}

	.add-btn {
		margin: 20rpx;
		background: #2979ff;
		color: white;
	}

	.dialog-container {
		width: 650rpx;
		background: white;
		border-radius: 16rpx;
	}

	.dialog-header {
		padding: 30rpx;
		display: flex;
		justify-content: space-between;
		align-items: center;
		border-bottom: 1rpx solid #eee;
	}

	.dialog-content {
		max-height: 800rpx;
		padding: 30rpx;
	}

	.form-row {
		margin-bottom: 40rpx;
	}

	.label {
		display: block;
		margin-bottom: 16rpx;
		color: #666;
	}

	.required::before {
		content: '*';
		color: red;
		margin-right: 8rpx;
	}

	.time-range {
		display: flex;
		align-items: center;
	}

	.time-range text {
		margin: 0 20rpx;
	}

	.selected-users {
		padding: 20rpx;
		background: #f5f5f5;
		border-radius: 8rpx;
	}

	.dialog-footer {
		display: flex;
		padding: 20rpx;
		border-top: 1rpx solid #eee;
	}

	.dialog-footer button {
		flex: 1;
		margin: 0 10rpx;
	}
	.search-box {
	  position: relative;
	  margin-bottom: 20rpx;
	}
	.search-input {
	  height: 80rpx;
	  padding: 0 80rpx 0 30rpx;
	  border: 1px solid #eee;
	  border-radius: 40rpx;
	  font-size: 28rpx;
	}
	.clear-btn {
	  position: absolute;
	  right: 30rpx;
	  top: 50%;
	  transform: translateY(-50%);
	  font-size: 40rpx;
	  color: #999;
	}
	.result-list {
	  max-height: 600rpx;
	  border: 1px solid #f5f5f5;
	  border-radius: 10rpx;
	}
	.result-item {
	  padding: 25rpx;
	  border-bottom: 1px solid #f5f5f5;
	  font-size: 28rpx;
	}
	.result-item:active {
	  background-color: #f9f9f9;
	}
	.empty-tip {
	  padding: 30rpx;
	  text-align: center;
	  color: #999;
	}
</style>